package cn.gov.cus.rmftquartz.config;

import com.atomikos.jdbc.AtomikosDataSourceBean;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import javax.sql.DataSource;
import java.util.Properties;

/**
 * //import org.springframework.context.annotation.Primary;相比gbase的少了这个，应该是主数据源的意思。下面的方法还少了@Primary注解。
 * @author wxming.
 * @date 2018/2/9.
 */
@Configuration
@MapperScan(basePackages = GBaseDataSourceConfig.PACKAGE,sqlSessionTemplateRef = "gbaseSqlSessionTemplate")
public class GBaseDataSourceConfig {
    static final String PACKAGE ="cn.gov.cus.rmftquartz.mappers.gbase";

    @Value("${datasource.gbase.gind.url}")
    private String url;
    @Value("${datasource.gbase.gind.username}")
    private String user;
    @Value("${datasource.gbase.gind.password}")
    private String password;
    @Value("${datasource.gbase.gind.driver-class-name}")
    private String driverClassName;
    @Value("${datasource.gbase.gind.maxPoolSize}")
    private Integer maxPoolSize;

    @Bean(name = "gbaseDataSource")
    @Autowired
    public DataSource gbaseDataSource(Environment env){
        AtomikosDataSourceBean atomikosDataSource = new AtomikosDataSourceBean();
        Properties prop = OracleDataSourceConfig.getDataSourceProperties(env,"datasource.gbase.gind.");
        atomikosDataSource.setXaDataSourceClassName("com.alibaba.druid.pool.xa.DruidXADataSource");
        atomikosDataSource.setUniqueResourceName("gbaseDB");
        //因为大量多线程跑数据，限制了数据库的连接池最大为5,配置里配了5。
        atomikosDataSource.setMaxPoolSize(maxPoolSize);
        atomikosDataSource.setXaProperties(prop);
        return atomikosDataSource;
    }

    @Bean(name = "gbaseSqlSessionFactory")
    public SqlSessionFactory gbaseSqlSessionFactory(@Qualifier("gbaseDataSource") DataSource gbaseDataSource) throws Exception{
        final SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();

        org.apache.ibatis.session.Configuration config = new org.apache.ibatis.session.Configuration();
        config.setMapUnderscoreToCamelCase(false);//特殊需求，Gbase数据库的po类字段映射没有按驼峰命名来，而是直接和数据库里的一样全是大写，且带下划线。
        sessionFactoryBean.setConfiguration(config);

        sessionFactoryBean.setDataSource(gbaseDataSource);
        return sessionFactoryBean.getObject();
    }

    @Bean(name = "gbaseSqlSessionTemplate")
    public SqlSessionTemplate mydbSqlSessionTemplate(@Qualifier("gbaseSqlSessionFactory")SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}


